import axios from 'axios';
import { message, message as Message } from 'antd';
import { WindManUtils } from '../util/utils';

const baseUrl = 'https://lwa.hanlingsha.love';

const instance = axios.create({
    // 超时时间
    timeout: 6000,
    // 响应前处理
    transformResponse: (responseData) => {
        return responseData;
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
});

// 请求拦截器
instance.interceptors.request.use((config) => {
    return config;
}, (err) => {
    console.error('- error 2: ', err);
    Message.error({ message: '请求超时!' });
    return Promise.reject('err');
});
// 响应拦截
instance.interceptors.response.use(function(response) {
    const { status, data, statusText, config } = response;
    if (status === 200) {
        try {
            // 后端报错可能返回非 json 格式化异常 try - catch
            const responseObeject = JSON.parse(data);
            if (responseObeject.errorCode === 901) {
                // TODO jump to login page
                WindManUtils.removeAllStorage();
                message.error(responseObeject.errorMessage, 1, () => {
                    window.location.pathname = '/login';
                });
            }
            if (config.headers.hasOwnProperty('X-SHOW-ERROR')) {
                console.log('get X-SHOW-ERROR, return response data');
                return responseObeject;
            }
            if (responseObeject.errorCode !== 0) {
                Message.error(responseObeject.errorMessage);
                return Promise.reject();
            }
            return responseObeject;
        } catch (error) {
            Message.error('网络异常');
            console.log(error);
        }
    } else {
        Message.error(`${status}-${statusText}`);
        return response;
    }
}, function(error) {
    // 对响应错误做点什么
    if (error.message.includes('timeout')) {
        Message.error('请求超时,请刷新重试').then( () => {
            window.location.pathname = '/'
        });
    }
    return Promise.reject(error);
});
export default {
    get: (url, params = {}, config = {}) => {
        const userInfo = WindManUtils.getStorage('user_info');
        let realUrl = `${baseUrl}${url}`;
        if (userInfo) {
            params['userId'] = userInfo.userId;
            params['token'] = userInfo.token;
        }
        const paramsRequest = { params: {...params}, ...config };
        return instance.get(realUrl, paramsRequest);
    },

    post: (url, params = {}, config = {}) => {
        const userInfo = WindManUtils.getStorage('user_info');
        let realUrl = `${baseUrl}${url}`;

        if (userInfo) {
            params['userId'] = userInfo.userId;
            params['token'] = userInfo.token;
        }

        const paramsForm = new FormData();
        for (const key in params) {
            paramsForm.append(key, params[key]);
        }
        const requestConfig = { ...config };

        return instance.post(realUrl, paramsForm, requestConfig);
        // return instance.post(requestUrl, Qs.stringify(paramss), option);
    },
    delete: (url, params, option) => {
        return instance.delete(url, Object.assign({
            params
        }, option));
    }
};
